package tpenchere.controllers;

import java.util.EventObject;
import java.util.Map;

import tpenchere.model.User;
import tpenchere.service.Client;
import tpenchere.service.EnchereServiceOperations;
import tpenchere.service.SessionHolder;
import tpenchere.ui.*;
import tpenchere.application.*;

import javax.swing.ActionMap;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.Action;
import javax.swing.JPanel;
import org.jdesktop.application.Application;
import org.jdesktop.application.Application.ExitListener;

import tpenchere.ui.AbstractView.ViewType;
import tpenchere.ui.contents.LoginWindow;

public class MainWindowController implements ExitListener, ControllerInterface {
	private final ActionMap actionMap = MainApplication.getApplication()
			.getContext().getActionMap(MainWindowController.class, this);
	private final ResourceMap resourceMap = MainApplication.getApplication()
			.getContext().getResourceMap(MainWindowController.class);
	
	private Client client = Client.getInstance();
	private SessionHolder session = SessionHolder.getInstance();
	
	MainWindow mainWindow;

	public MainWindowController(MainWindow mainWindow) {
		MainApplication.getApplication().addExitListener(this);
		this.mainWindow = mainWindow;
	}

	@Action(name = "view.register")
	public void register() {
		mainWindow.switchToView(ViewType.REGISTER);
	}

	@Action(name = "view.login")
	public void login() {
		mainWindow.switchToView(ViewType.LOGIN);
	}
	
	@Action(name = "menuBar.logged.changeUser")
	public void changeUser() {
		mainWindow.switchToView(ViewType.LOGIN);
	}

	@Action(name = "menuBar.connection.unlog")
	public void unlog() {
		session.clearSession();
		mainWindow.switchToView(ViewType.LOGIN);
	}

	@Action(name = "menuBar.about.showAbout")
	public void showAbout() {
		JOptionPane.showMessageDialog(null, 
				resourceMap.getString("dialog.about.content"), 
				resourceMap.getString("dialog.about.title"),
				JOptionPane.INFORMATION_MESSAGE);
	}

	@Action(name = "menuBar.connection.close")
	public void close() {
		MainApplication.getApplication().exit();
	}

	public ActionMap getActionMap() {
		return actionMap;
	}

	public boolean canExit(EventObject arg0) {
		int ret = JOptionPane.showConfirmDialog(new JFrame(), resourceMap
				.getString("dialog.exitConfirm.text"), resourceMap
				.getString("Application.title"), JOptionPane.YES_NO_OPTION,
				JOptionPane.WARNING_MESSAGE);
		// the user select yes (0)
		return ret == 0;
	}

	public void willExit(EventObject arg0) {
		// TODO Auto-generated method stub

	}
}
